<?php

class Helper_Related
{
    public $view;
    
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }

    function related($nid,$limit=10)
    {
        $related=array();
        $nodes_rel=array();
        
        $tagsTbl=new Application_Model_TagsDb();
        $nodeTbl=new Application_Model_NodeDb();
        
        $tags=$tagsTbl->fetchTagsByNodeId($nid,$limit);
        
        foreach($tags as $tag)
        {
            if (count($related)>=$limit) break;
            
            $_tags=$tagsTbl->fetchTagsByClause(array(
                                                'tag=?'=>$tag,
                                                'nid<>?'=>$nid,
                                                ),true,$limit);
                         
            foreach($_tags as $_tag)
            {       
                if (count($related)>=$limit) break;
          
                $node=$nodeTbl->fetchNodeById($_tag->nid);
                
                if (in_array($node->id,$nodes_rel)) continue;
                
                if (!$node->isExists() || $node->isPublished()) continue;
                
                $related[]=$this->item($node);
                
                $nodes_rel[]=$node->id;
            }
        }
        
        if (count($related)<$limit)
        {
            $node=$nodeTbl->fetchNodeById($nid);
            
            list($nodes,$paginator)=$nodeTbl->getNodesPageByTypeAndCategory('node',$node->category,1,$limit+1,true);
            
            foreach($nodes as $_node)
            {
                if ($_node->id==$nid) continue;
                
                if (count($related)>=$limit) break;
                            
                $node=$nodeTbl->fetchNodeById($_node->id);
                
                if (in_array($node->id,$nodes_rel)) continue;
                
                $related[]=$this->item($node);
                
                $nodes_rel[]=$node->id;
            }
        }
        
        if (count($related)==0) return;
        
        return '<h3 class="related-caption">'.Zend_Registry::get('locale')->_('See also').':</h3><ul>'.implode("\n",$related).'</ul>';
    }
    
    public function item($node)
    {
        $url=!empty($node->url_alias) ? $this->view->fixUrl('page/'.$node->url_alias).'.html' : $this->view->fixUrl('node/id/'.$node->id);
        
        return '<li class="related-nodes-item"><span class="related-title">'.$node->title.'</span><span class="related-description">'.$node->short_text.'<span class="related-link"><a href="'.$url.'">'.Zend_Registry::get('locale')->_('Read more').'</a></span></span></li>';
    }
}
